# coding: utf-8
import requests

try:
    import cookielib
except:
    import http.cookiejar as cookielib
import re
import time
import os.path

agent = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) ' \
        'Chrome/56.0.2924.87 Mobile Safari/537.36'
headers = {
    # "Host": "www.zhihu.com",
    # "Referer": "https://www.zhihu.com/",
    'User-Agent': agent
}
session = requests.session()
session.cookies = cookielib.LWPCookieJar(filename='cookies')
try:
    session.cookies.load(ignore_discard=True)
except:
    print("Cookie 未能加载")


def get_xsrf():
    """_xsrf 是一个动态变化的参数"""
    index_url = 'http://172.16.172.180:8000/user/login/'
    # 获取登录时需要用到的_xsrf
    index_page = session.get(index_url, headers=headers)
    if index_page.status_code != 200:
        html = index_page.content
        pattern = r"name='csrfmiddlewaretoken' value='(.*?)'"
        # 这里的_xsrf 返回的是一个list
        _xsrf = re.findall(pattern, html, re.MULTILINE)
        return _xsrf[0]


def login(secret, account):
    _xsrf = get_xsrf()
    # headers["X-Xsrftoken"] = _xsrf
    # headers["X-Requested-With"] = "XMLHttpRequest"
    post_url = "http://172.16.172.180:8000/user/login/"
    postdata = {
        'csrfmiddlewaretoken': _xsrf,
        'username': account,
        'password': secret,
    }
    login_page = session.post(post_url, data=postdata, headers=headers)
    print login_page.status_code
    session.cookies.save()


if __name__ == '__main__':
    # login('user2', 'user2')
    data = {"name": "我来试试", "capacity": "13", "nums": 2, "expired": "2",
            'csrfmiddlewaretoken': session.cookies._cookies.get("172.16.172.180")['/']['csrftoken'].value}
    print session.cookies._cookies.get("172.16.172.180")['/']['csrftoken'].value
    r = session.post("http://172.16.172.180:8000/host/cloud_disk/", headers=headers, json=data, )
    print r.content
    pass
